package cn.fzkj.common.utils;

import cn.fzkj.framework.exception.client.ClientException;
import cn.fzkj.framework.security.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 安全服务工具类
 */
public class SecurityUtil {

    public static String getUserName(){
        try {
            return getLoginUser().getUsername();
        }catch (Exception e){
            throw new ClientException("获取用户账户异常");
        }
    }

    /**
     * 获取用户
     * @return
     */
    public static LoginUser getLoginUser(){
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e){
            throw new ClientException("获取用户信息异常");
        }
    }

    /**
     * 获取 Authentication
     * @return
     */
    public static Authentication getAuthentication(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     * @param password 明文密码
     * @return 密文密码
     */
    public static String encryptPassword(String password){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder.encode(password);
    }

    /**
     * 比较密码是否相同
     * @param realPassword 真实的密码
     * @param encodePassword 加密后密码
     * @return
     */
    public static boolean matchePassword(String realPassword, String encodePassword){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder.matches(realPassword, encodePassword);
    }

}
